<?php
/**
 * Created by PhpStorm.
 * User: 王崇全
 * Date: 2017/12/14
 * Time: 18:04
 */

namespace app\common\model;

use think\Db;
use think\Model;

class Article extends Model
{
    const TAB_NAME          = "article";
    const TAB_NAME_CATEGORY = "article_category";

    /**
     * 创建文章
     * @author 王崇全
     * @date
     * @param string $title   标题
     * @param string $gid     分组ID
     * @param string $content 内容
     * @param string $cover   封面
     * @return string 文章ID
     */
    public function add(string $title, string $gid, string $content = '', string $cover = '')
    {

        $now = date("Y-m-d H:i:s");

        $id = uuid();
        $this->insert([
            "id"          => $id,
            "category_id" => $gid,
            "title"       => $title,
            "cover"       => $cover,
            "content"     => $content,
            "create_time" => $now,
            "update_time" => $now,
            "delete_time" => null,
        ]);

        return $id;

    }

    /**
     * 编辑文章
     * @author 王崇全
     * @date
     * @param string      $id      ID
     * @param string|null $title   标题
     * @param string|null $gid     分组ID
     * @param string|null $content 内容
     * @param string|null $cover   封面
     * @return int|string 修改成功数
     * @throws \Exception
     */
    public function edit(string $id, string $title = null, string $gid = null, string $content = null, string $cover = null)
    {
        $data = [];
        if (isset($title)) {
            $data["title"] = $title;
        }
        if (isset($gid)) {
            $data["category_id"] = $gid;
        }
        if (isset($content)) {
            $data["content"] = $content;
        }
        if (isset($cover)) {
            $data["cover"] = $cover;
        }

        if (!empty($data)) {
            $data['update_time'] = date('Y-m-d H:i:s');
        }

        return $this->where("id", $id)
                    ->update($data);
    }

    /**
     * 获取文章列表
     * @author 王崇全
     * @date   2018/12/19 17:06
     * @param array $map      ["cid"=>栏目ID,"title"=>文章标题关键词,"st"=>开始时间,"et"=>截止时间]
     * @param int   $pageNo   页码
     * @param int   $pageSize 页幅
     * @return array [[
     *                        [
     *                        "id"=>ID,
     *                        "title"=>标题,
     *                        "cover"=>封面,
     *                        "create_time"=>创建时间,
     *                        "delete_time"=>删除时间,
     *                        "content"=>内容,
     *                        "catalog_name"=>栏目名称,
     *                        ],...
     *                        ],个数]
     * @throws
     */
    public function getList(array $map = [], int $pageNo = DEF_PAGE_NO, int $pageSize = DEF_PAGE_SIZE)
    : array {

        $dbw = Db::name(self::TAB_NAME)
                 ->alias("a")
                 ->whereNull("delete_time");

        //栏目检索
        if (isset($map["cid"])) {
            $child = Db(self::TAB_NAME_CATEGORY)
                ->where("pid")
                ->column("id");
            if (!$child) {
                $dbw->where("a.category_id", $map["cid"]);
            } else {
                $dbw->where("a.category_id", "IN", $child);
            }
        }

        if (isset($map["title"])) {
            $dbw->where("a.title", "like", "%{$map["title"]}%");
        }
        if (isset($map["st"])) {
            $dbw->whereTime("a.create_time", ">=", $map["st"]);
        }
        if (isset($map["et"])) {
            $dbw->whereTime("a.create_time", "<=", $map["et"]);
        }


        $count = $dbw->count();
        if (!$count) {
            return [
                [],
                0,
            ];
        }

        $list = $dbw->field([
            "a.id",
            "a.title",
            "a.cover",
            "a.create_time",
            "a.delete_time",
            "a.content",
            "g.title" => "catalog_name",
        ])
                    ->leftJoin(self::TAB_NAME_CATEGORY." g", "a.category_id=g.id")
                    ->order(["a.create_time" => "desc"])
                    ->page($pageNo, $pageSize)
                    ->select();

        if (!$list) {
            return [
                [],
                0,
            ];
        }

        return [
            $list,
            $count,
        ];
    }

    /**
     * 删除文章
     * @author 王崇全
     * @param string $id 分组id
     */
    public function del(string $id)
    {
        $this->where("id", $id)
             ->update(['delete_time' => date('Y-m-d H:i:s')]);
    }

    /**
     * 获取文章信息
     * @author 王崇全
     * @date
     * @param string $id
     * @return array [
     *                  "id"=>ID,
     *                  "category_id"=>分组ID,
     *                  "title"=>标题,
     *                  "content"=>内容,
     *                  "create_time"=>创建时间,
     *                  ]
     * @throws \Exception
     */
    public function getInfo(string $id)
    {
        return $this->field([
            "id",
            "category_id",
            "title",
            'cover',
            'content',
            "create_time",
        ])
                    ->where("id", $id)
                    ->find();
    }

    /**
     * 获取文章封面
     * @author 王崇全
     * @date
     * @param string $id
     * @return mixed
     */
    public function getCover(string $id)
    {
        return $this->where("id", $id)
                    ->value("cover");
    }

    /**
     * 获取某分组下的文章数目
     * @author 王崇全
     * @date
     * @param string $gid 分组ID
     * @return int 文章数目
     */
    public function getCount(string $gid)
    {
        return $this->where("category_id", $gid)
                    ->count();
    }

    /**
     * 获取某分组下的第一篇文章的ID
     * @author 王崇全
     * @date
     * @param string $gid 分组ID
     * @return string 文章ID
     */
    public function getFirst(string $gid)
    {
        return $this->where("category_id", $gid)
                    ->order(["create_time" => "DESC"])
                    ->value("id");
    }

}